<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MClassify;
use App\Models\MFeedback;
use App\Models\MNews;
use App\Models\MNotices;
use App\Models\MProtocols;
use App\Models\MSlug;
use App\Models\MSlugClassify;
use Illuminate\Http\Request;

/**
 * 信息管理控制器
 */
class ContentController extends Controller
{
    /**
     * 分类列表界面
     */
    public function classifyPage()
    {
        $this->data['classifies'] = MClassify::all();
        return view("admin.classifies")->with($this->data);
    }

    /**
     * 分类编辑界面
     */
    public function classifyEditPage($id)
    {
        $this->data['classify'] = MClassify::find($id);
        $this->data['classifies'] = MClassify::where('id', '!=', $id)->get();
        return view("admin.classify_edit")->with($this->data);
    }

    /**
     * 分类信息存储
     */
    public function classifySave(Request $request, $id)
    {
        if (!$this->validateReq($request, MClassify::editRulesWithMsg(0), MClassify::editRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }
        $classify = MClassify::find($id);
        $parent = MClassify::find($request->parent);
        if (empty($classify)) {
            $classify = new MClassify();
        }

        if ($classify->saveData($parent, $request->title, $request->intro, $request->sort)) {
            $this->data = $this->makeJsCode(0, "保存成功！");
        } else {
            $this->data = $this->makeJsCode(1, "保存失败！");
        }

        return response()->json($this->data);
    }

    /**
     * 文章分类删除
     */
    public function classifyDel($id)
    {
        //如果分类下还有文章，则不可以删除
        if (MNews::where('cid', $id)->count() > 0) { //
            $this->data = $this->makeJsCode(1, "此分类下还有文章未删除！");
        } else {
            MClassify::destroy($id);
            $this->data = $this->makeJsCode(0, "删除成功！");
        }
        return back()->with($this->data);
    }


    /**
     * 文章列表界面
     * $cid = 0 获取全部的文章
     */
    public function newsPage(Request $request, $index = 1)
    {
        //开启分页搜索支持
        $this->fyInit(route("admin.news"), 20, $request->getQueryString());
        $query = (new MNews())->query();

        //按分类筛选
        if ($request->has('classify')) {
            $query = $query->where('cid', $request->classify);
        }

        //按时间过滤
        if ($request->has(['start', 'end'])) {
            $query = $query->where('time', '>=', strtotime($request->start))
                ->where('time', '<=', strtotime($request->end));
        }

        //按标题搜索
        if ($request->has('search_str')) {
            $query = $query->where('title', 'like', "%" . $request->search_str . "%");
        }

        //排序
        if ($request->has('sort_type')) {
            if ($request->sort_type == 1) {//按修改时间降序
                $query = $query->orderBy("time", "desc");
            } elseif ($request->sort_type == 2) {//按修改时间升序
                $query = $query->orderBy("time", "asc");
            }
        }

        $this->fyCalc($query->count(), $index);
        $this->data['news'] = $query->skip($this->fy_pgOffset)->take($this->fy_pgSize)->orderBy('time', 'desc')->get();
        $this->data['classifies'] = MClassify::all();
        $this->fyViewInit($this->data);
        return view("admin.news")->with($this->data);
    }

    /**
     * 文章编辑界面
     */
    public function newsEditPage($id)
    {
        $this->data['news'] = MNews::find($id);
        $this->data['classifies'] = MClassify::all();
        return view("admin.news_edit")->with($this->data);
    }

    /**
     * 文章内容存储
     */
    public function newSave(Request $request, $id)
    {
        if (!$this->validateReq($request, MNews::editRulesWithMsg(0), MNews::editRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        //检查文章分类
        $classify = MClassify::find($request->cid);
        if (empty($classify)) {
            $this->data = $this->makeJsCode(1, "请必须选择文章类别！");
            return response()->json($this->data);
        }
dd($request->file);
        //接收封面图片
        $imgPath = null;
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            $file = $request->file('file');
            $filename = md5_file($file->getPathname()) . "." . $file->getClientOriginalExtension();   //md5 + 扩展名
            $file->move('uploads/imgs/', $filename);
            $imgPath = 'uploads/imgs/' . $filename;
        }

        $news = MNews::find($id);
        if (empty($news)) {
            $news = new MNews();
        }

        if ($news->saveData($classify, $request->title, $request->input("content"),$imgPath)) {
            $this->data = $this->makeJsCode(0, "保存成功！");
        } else {
            $this->data = $this->makeJsCode(1, "保存失败！");
        }

        return response()->json($this->data);
    }

    /**
     * 文章删除处理
     */
    public function newsDel($id)
    {
        MNews::destroy($id);
        $this->data = $this->makeJsCode(0, "删除成功！");
        return back()->with($this->data);
    }


    /**
     * 公告列表界面
     * @param int $index
     * @return $this
     */
    public function noticesPage($index = 1)
    {
        $this->fyInit(route("admin.notices"), 20);
        $this->fyCalc(MNotices::count(), $index);
        $this->data['notices'] = MNotices::skip($this->fy_pgOffset)->take($this->fy_pgSize)
            ->orderBy('time', 'desc')->get();
        $this->fyViewInit($this->data);
        return view("admin.notices")->with($this->data);
    }

    /**
     * 公告编辑界面
     */
    public function noticesEditPage($id)
    {
        $this->data['notices'] = MNotices::find($id);
        return view("admin.notices_edit")->with($this->data);
    }

    /**
     * 公告内容存储
     */
    public function noticesSave(Request $request, $id)
    {
        if (!$this->validateReq($request, MNotices::editRulesWithMsg(0), MNotices::editRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        $notices = MNotices::find($id);
        if (empty($notices)) {
            $notices = new MNotices();
        }

        if ($notices->saveData($request->title, $request->input("content"),
            strtotime($request->start), strtotime($request->end))
        ) {
            $this->data = $this->makeJsCode(0, "保存成功！");
        } else {
            $this->data = $this->makeJsCode(1, "保存失败！");
        }

        return response()->json($this->data);
    }

    /**
     * 公告删除处理
     */
    public function noticesDel($id)
    {
        MNotices::destroy($id);
        $this->data = $this->makeJsCode(0, "删除成功！");
        return back()->with($this->data);
    }

    /**
     * 会员咨询列表
     * $flag = 0(未回复咨询)
     * $flag = 1(已回复咨询)
     */
    public function feedbackPage(Request $request, $flag = 0, $index = 1)
    {
        //开启分页搜索支持
        $this->fyInit(route('admin.feedback', ['flag' => $flag]), 20, $request->getQueryString());
        $query = (new MFeedback())->query()->where("status", $flag);

        //按时间过滤
        if ($request->has(['start', 'end'])) {
            $query = $query->where('time', '>=', strtotime($request->start))
                ->where('time', '<=', strtotime($request->end));
        }

        //按会员帐号搜索
        if ($request->has('search_type') && $request->search_type == 1) {
            $query = $query->where('uname', 'like', "%" . $request->search_str . "%");
        }

        //按用户ID搜索
        if ($request->has('search_type') && $request->search_type == 2) {
            $query = $query->where('uid', $request->search_str);
        }

        //按咨询内容搜索
        if ($request->has('search_type') && $request->search_type == 3) {
            $query = $query->where('content', 'like', "%" . $request->search_str . "%");
        }

        //按咨询ID搜索
        if ($request->has('search_type') && $request->search_type == 4) {
            $query = $query->where('id', $request->search_str);
        }

        //排序
        if ($request->has('sort_type')) {
            if ($request->sort_type == 1) {         //按修改时间降序
                $query = $query->orderBy("time", "desc");
            } elseif ($request->sort_type == 2) {   //按修改时间升序
                $query = $query->orderBy("time", "asc");
            }
        }

        $this->fyCalc($query->count(), $index);
        $this->data['feedbacks'] = $query->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)
            ->where('status', $flag)
            ->orderBy('time', 'desc')
            ->get();

        $this->fyViewInit($this->data);

        $this->data['flag'] = $flag;
        return view('admin.feedbacks')->with($this->data);
    }

    /**
     * 会员咨询回复界面
     */
    public function feedbackEditPage(Request $request, $id, $index = 1)
    {
        //开启分页
        $this->fyInit(route('admin.feedback.edit', ['id' => $id]), 5, $request->getQueryString());
        $query = (new MFeedback())->query();

        $this->fyCalc($query->count(), $index);
        $this->data['feedback_reply'] = $query->skip($this->fy_pgOffset)->take($this->fy_pgSize)->orderBy('time', 'desc')->get();
        $this->fyViewInit($this->data);

        $this->data['id'] = $id;
        return view('admin.feedback_edit')->with($this->data);
    }

    /**
     * 回复会员咨询信息保存
     */
    public function feedbackReply(Request $request, $id)
    {
        if (!$this->validateReq($request, MFeedback::editRulesWithMsg(0), MFeedback::editRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        $reply = MFeedback::find($id);
        if (empty($reply)) {
            $reply = new MFeedback();
        }

        if ($reply->saveData($request->input('content'))) {
            $this->data = $this->makeJsCode(0, "保存成功！");
        } else {
            $this->data = $this->makeJsCode(1, "保存失败！");
        }


        return response()->json($this->data);
    }

    /**
     * 删除会员咨询
     */
    public function feedbackDel($id)
    {
        MFeedback::destroy($id);
        $this->data = $this->makeJsCode(0, "删除成功！");
        return back()->with($this->data);
    }

    /**
     * 会员注册协议界面
     */
    public function protocolPage()
    {
        $this->data['protocol'] = MProtocols::first();
        return view('admin.protocol-edit')->with($this->data);
    }

    public function protocolSave(Request $request)
    {
        $protocol = MProtocols::first();

        if (empty($protocol)) {
            $protocol = new MProtocols();
        }

        $protocol->title = $request->title;
        $protocol->content = $request->input('content');
        $protocol->time = time();

        if ($protocol->save()) {
            $this->data = $this->makeJsCode(0, '操作成功！');
        } else {
            $this->data = $this->makeJsCode(1, '操作失败！');
        }
        return response()->json($this->data);
    }
}